Breadth- First Search Algorithm
The Breadth-First Search (BFS) Algorithm is a graph traversal technique used to explore all the vertices and edges of a graph systematically, prioritizing the expansion of nodes at the current depth level before moving to nodes at a deeper level. It is an intuitive and efficient way to search through a graph data structure, which consists of vertices (nodes) and edges (connections between nodes). BFS is particularly useful in finding the shortest path between two nodes in a graph, as well as for applications that require visiting all nodes, such as analyzing social networks or web crawling.
BFS starts at a specified source node and visits all its neighboring nodes before moving to their neighbors. The algorithm uses a queue data structure to store the nodes yet to be explored. Initially, the queue contains only the source node. As BFS progresses, the algorithm dequeues the front node, explores its neighbors, and enqueues any unvisited neighbors. This process is repeated until the queue is empty, which indicates that all reachable nodes have been visited. BFS ensures a complete, level-by-level traversal of the graph, providing an optimal solution for problems that require the shortest path or minimum number of steps.
/*
Petar 'PetarV' Velickovic
Algorithm: Breadth-First Search
*/
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <iostream>
#include <vector>
#include <list>
#include <string>
#include <algorithm>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <complex>
#define MAX_N 5001
using namespace std;
typedef long long lld;
struct Node
{
vector<int> adj;
};
Node graf[MAX_N];
bool mark[MAX_N];
//Algoritam za pretrazivanje grafa u sirinu
//Slozenost: O(V + E)
inline void BFS(int start)
{
queue<int> bfs_queue;
bfs_queue.push(start);
while (!bfs_queue.empty())
{
int xt = bfs_queue.front();
bfs_queue.pop();
mark[xt] = true;
printf("Traversing Node ID %d\n", xt);
for (int i=0;i<graf[xt].adj.size();i++)
{
if (!mark[graf[xt].adj[i]])
{
bfs_queue.push(graf[xt].adj[i]);
mark[graf[xt].adj[i]] = true;
}
}
}
}
int main()
{
graf[0].adj.push_back(1);
graf[0].adj.push_back(2);
graf[2].adj.push_back(3);
graf[3].adj.push_back(4);
BFS(0);
return 0;
}